package dao;

import bean.OrderBean;
import com.avaje.ebean.ExpressionList;
import com.google.gson.Gson;
import models.CustomerInformation;
import models.CustomerOrder;
import models.ProductOfOrder;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Gipxy group
 * Date: 4/30/12
 */
public class OrderManager {
    public static void save(OrderBean orderBean) {
        CustomerOrder o = new CustomerOrder();
        o.soDonHang = orderBean.soDonHang;

        if (orderBean.ngayDatHang.indexOf("/") > 0){
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            try {
                o.ngayDatHang = formatter.parse(orderBean.ngayDatHang);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        else if (orderBean.ngayDatHang.indexOf("-") > 0){
            DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
            try {
                o.ngayDatHang = formatter.parse(orderBean.ngayDatHang);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        else {
            o.ngayDatHang = Calendar.getInstance().getTime();
        }
        o.khachHang = CustomerInformation.find.byId(new Long(orderBean.customerID));
        o.allProduct = new ArrayList<ProductOfOrder>();
        o.save();

        if (orderBean.productOrdersAsJson!=null) {
            ProductOfOrder[] productOfOrders = fromJson(orderBean.productOrdersAsJson);
            for (ProductOfOrder p : productOfOrders)      {
                p.customerOrder =  o;
                p.save();
                //o.allProduct.add(p);
            }
        }


        //ExpressionList<CustomerOrder> donHang = CustomerOrder.find.where().ilike("soDonHang", "%" + o.soDonHang + "%");
        CustomerOrder donHang = CustomerOrder.find.byId(o.id);



        System.out.println("jjj="+donHang.soDonHang);
        System.out.println("jjj="+donHang.allProduct.size());
        System.out.println("ddd=" + ProductOfOrder.find.all().size());
    }

    public static ProductOfOrder[] fromJson(String json) {
        Gson gson = new Gson();
        ProductOfOrder[] all = gson.fromJson(json, ProductOfOrder[].class);
        return all;
    }

    public static Map<String,String> allNewOrders() {
        LinkedHashMap<String,String> options = new LinkedHashMap<String,String>();
        for(CustomerOrder c: CustomerOrder.find
                //.where().eq("")          : new order only
                .orderBy("soDonHang").findList()) {
            options.put(c.id.toString(), c.soDonHang);
        }
        return options;
    }
}
